<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015-5-20
 * Time: 10:02
 * this file is for single image upload function
 */

namespace doumiaoduo\ueditor;


use EasyWeChat\Foundation\Application;
use yii\widgets\InputWidget;
use yii\helpers\Html;
use yii\helpers\Json;
use yii\helpers\ArrayHelper;

class ImageUploadWechat extends InputWidget
{
    public $clientOptions = [];

    public $serverParam = [];

    public $buttonOptions = [];

    public $view;
    public $asset;

    public function init()
    {
        parent::init();
        $id = str_replace('-', '_', $this->options['id']);
        if (isset($this->clientOptions['serverUrl'])) {
            $this->clientOptions['serverUrl'] = str_replace('action', 'uploadwechatimage', $this->clientOptions['serverUrl']);
            $this->clientOptions['serverUrl'] = str_replace(urlencode('action'), 'uploadwechatimage', $this->clientOptions['serverUrl']);
            $this->clientOptions['serverUploadvideotoWechatUrl'] = str_replace(urlencode('uploadwechatimage'), 'uploadvideotowechat', $this->clientOptions['serverUrl']);
        }
        $this->clientOptions['csrf-param'] = \Yii::$app->request->csrfParam;
        $this->clientOptions['csrf-token'] = \Yii::$app->request->getCsrfToken();
        $this->clientOptions['isShow'] = false;
        $this->buttonOptions['id'] = isset($this->buttonOptions['id']) ? $this->buttonOptions['id'] : "image_upload_button_{$this->options['id']}";
        $this->view = $this->getView();
        $this->asset = ImageUploadWechatAsset::register($this->view);
    }

    public function run()
    {
        $pathInfo=\Yii::$app->request->getPathInfo();

        $strHtml = '';

        $strHtml .= '<div style="width:50%;"><input type="radio" name="uploadtype"  style="width:20%" class="uploadtype" value="image" id="radio_image" checked><label for="radio_image">图片</label>';
        if(!$pathInfo=='information/addmess'){
            $strHtml .= '<input type="radio" name="uploadtype" class="uploadtype" value="video"  id="radio_video" style="width:20%"><label for="radio_video">视频</label>';
        }
        $strHtml.='</div>';
        $strHtml .= '<div class="am-u-sm-7 cj-alert-input">';
        $strHtml .= Html::hiddenInput('growth_medias', '', ['id' => 'growth_upload_medias','class' => 'am-modal-prompt-input']);
        if ($this->hasModel()) {
            $strHtml .= Html::activeTextInput($this->model, $this->attribute, $this->options);
        } else {
            $strHtml .= Html::textInput($this->name, $this->value, $this->options);
        }
        $strHtml .= '</div><div class="am-u-sm-4 cj-alert-bot" id="uploadimg"><span id="upload_growth_course_emphasis">添加文件</span><input type="text" style="display:none;" id="upload_growth_course_emphasis_button_tst"/>
                    </div>';
        $strHtml .= '<div class="am-u-sm-4 cj-alert-bot" id="uploadvideo" style="display:none"><input type="file" id="upload_growthvideo_course_emphasis" name="upfile" capture="camera" accept="video/mp4" name="" value="">选择视频</div>';
        echo $strHtml;
        $this->registerClientScript();
    }

    public function registerClientScript()
    {
        if(isset(\Yii::$app->controller->module)&&\Yii::$app->controller->module->id=='app-wechatzht'){
            $options = \Yii::$app->params['options_zht'];
        }else{
            $options = \Yii::$app->params['options'];
        }
        $pathInfo=\Yii::$app->request->getPathInfo();
        $application = new Application($options);
        $js = $application->js;
        $config = $js->config(array('chooseImage', 'uploadImage'), false);
        $jss = "";
        $jss .= <<<JS
            var upload_url = '{$this->clientOptions['serverUrl']}';
            var uploadvideo_url = '{$this->clientOptions['serverUploadvideotoWechatUrl']}';
            wx.config($config);
            $(document).on('click','#upload_growth_course_emphasis',function(){
                wx.chooseImage({
                    count: 1, // 默认9
                    sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
                    sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
                    success: function (res) {
                        var localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
                        $('#growth_upload_medias').val(localIds);
                        $('#upload_growth_course_emphasis_button_tst').trigger('click');
                    }
                });
            });
            $('#upload_growth_course_emphasis_button_tst').click(function(){
            var localIds = $('#growth_upload_medias').val();
                wx.uploadImage({//上传图片到微信端andoss
                    localId:localIds,
                    isShowProcessTips:1,
                    success:function(res){
                        var serverId = res.serverId;
                        $.post(upload_url,{'{$this->clientOptions['csrf-param']}': '{$this->clientOptions['csrf-token']}',ajax:'wechatimage',media_id:serverId},function(data){
                            alert(data.state);
                            if(data.state == 'SUCCESS'){
                                $('#{$this->options['id']}').val(data.url);
                             }
                        });
                    },
                });
            });
            
            $(".uploadtype").change(function() {
                var selectedvalue = $("input[name='uploadtype']:checked").val();
                $('#{$this->options['id']}').val("");
                if(selectedvalue == 'image'){
                    $('#uploadimg').show();
                    $('#uploadvideo').hide();
                }else{
                    $('#uploadimg').hide();
                    $('#uploadvideo').show();
                }
            });
            
            $('#upload_growthvideo_course_emphasis').change(function(){
                var video = document.getElementById('upload_growthvideo_course_emphasis');
                var path = video.value;
                 $.ajaxFileUpload
            (
                {
                    url: uploadvideo_url, //用于文件上传的服务器端请求地址
                    secureuri: false, //是否需要安全协议，一般设置为false
                    fileElementId: 'upload_growthvideo_course_emphasis', //文件上传域的ID
                    dataType: 'json', //返回值类型 一般设置为json
                    data: {'{$this->clientOptions['csrf-param']}': '{$this->clientOptions['csrf-token']}'},
                    success: function (data, status)  //服务器成功响应处理函数
                    {
                        
                        if(data.state == 'SUCCESS'){
                            alert('上传成功');
                            $('#{$this->options['id']}').val(data.url);
                        }else{
                            alert('对不起，上传失败');
                        }
                    },
                    error: function (data, status, e)//服务器响应失败处理函数
                    {
                        alert(e);
                    }
                }
            )
            })

JS;
        $this->view->registerJs($jss);
    }

}